package locating;

import impsoft.bots.reflection.GroundItem;
import impsoft.bots.reflection.PhysicalObject;
import impsoft.scripting.ibot.structs.AryanTile;
import base.DreamScript;
import base.DreamUtility;

public class ObjectFinder extends DreamUtility {

	public ObjectFinder(DreamScript cs) {
		super(cs);
	}

	public GroundItem getGroundItem(int... id) {
		return getGroundItem(id, null);
	}

	public GroundItem getGroundItem(int[] ids, AryanTile tile) {
		GroundItem closest = null;
		double closestDistance = 1000;

		AryanTile center = tile;
		if (tile == null) {
			center = cs.getLocation();
		}

		GroundItem[] objs = cs.getAllGroundItems();
		for (GroundItem obj : objs) {
			for (int id : ids) {
				if (obj.getID() == id) {
					double distance = obj.getLocation().distanceToPrecise(center);
					if (distance < closestDistance) {
						closest = obj;
						closestDistance = distance;
					}
				}
			}
		}

		return closest;
	}

	public PhysicalObject getPhysicalObject(int id) {
		return getPhysicalObject(new int[] { id }, cs.getLocation(), false, 17, false);
	}

	public PhysicalObject getPhysicalObject(int[] ids, AryanTile tile, boolean thisTileOnly, int maxDistance,
			boolean boundary) {
		PhysicalObject closest = null;
		double closestDistance = 1000;
		AryanTile center = tile;
		if (tile == null) {
			center = cs.getLocation();
		}

		PhysicalObject[] objs = null;
		if (boundary) {
			objs = cs.getAllBoundaryPhysicalObjects();
		} else {
			objs = cs.getAllInteractivePhysicalObjects();
		}

		for (PhysicalObject obj : objs) {
			for (int id : ids) {
				if (obj.getID() == id) {
					double distance = obj.getLocation().distanceToPrecise(center);
					if (distance < closestDistance && distance <= maxDistance) {
						closest = obj;
						closestDistance = distance;
						if (thisTileOnly && tile.equals(closest.getLocation())) {
							return closest;
						}
					}
				}
			}
		}

		if (closest == null) {
			return null;
		}

		if (!thisTileOnly || tile.equals(closest.getLocation())) {
			return closest;
		} else {
			return null;
		}
	}
}
